package com.gh.controller.api;


import com.alibaba.fastjson.JSON;
import com.gh.common.result.R;
import com.gh.entity.LendReturn;
import com.gh.hfb.RequestHelper;
import com.gh.service.LendReturnService;
import com.gh.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 还款记录表 前端控制器
 * </p>
 *
 * @author Eric
 * @since 2021-09-06
 */
@Slf4j
@Api(tags = "还款计划")
@RestController
@RequestMapping("/api/core/lend-return")
public class LendReturnController {

    @Resource
    private LendReturnService lendReturnService;

    @ApiOperation("获取列表")
    @GetMapping("list/{lendId}")
    public R list(@ApiParam(value = "标的id", required = true)
                  @PathVariable Long lendId) {
        List<LendReturn> list = lendReturnService.selectByLendId(lendId);
        return R.ok().data("list", list);
    }

    @ApiOperation("还款")
    @PostMapping("auth/commitReturn/{lendReturnId}")
    public R commitReturn(@ApiParam(value = "还款计划id", required = true)
                          @PathVariable Long lendReturnId, HttpServletRequest request) {
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        String formStr = lendReturnService.commitReturn(lendReturnId,userId);
        return R.ok().data("formStr",formStr);
    }

    @ApiOperation("还款异步回调")
    @PostMapping("notifyUrl")
    public String notifyUrl(HttpServletRequest request){
        //汇付宝向尚融宝发送请求时携带的参数
        Map<String, Object> map = RequestHelper.switchMap(request.getParameterMap());
        log.info("异步回调参数如下：{}", JSON.toJSONString(map));
        //校验签名
        if(RequestHelper.isSignEquals(map)){
            if("0001".equals(map.get("resultCode"))){
                return lendReturnService.notifyUrl(map);
            } else {
                log.info("还款结果异常");
                return "fail";
            }
        } else {
            log.info("签名错误");
            return "fail";
        }
    }
}

